#include "jointstatuswidget.h"
#include "tcpstatuswidget.h"
#include "mainwindow.h"
#include "tool_pushbutton.h"
#include "ui_mainwindow.h"

#include <qscrollarea.h>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //最大化最小化按钮
    // setWindowFlags(Qt::CustomizeWindowHint|Qt::WindowMinimizeButtonHint|Qt::WindowMaximizeButtonHint|Qt::WindowCloseButtonHint);
    setWindowFlags(Qt::FramelessWindowHint);  // 去除默认标题栏
    // 启用右键菜单
    ui->deviceTreeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->deviceTreeWidget, &QTreeWidget::customContextMenuRequested, this, &MainWindow::showContextMenu);

    connect(ui->deviceTreeWidget, &QTreeWidget::itemClicked, this, &MainWindow::onDeviceTreeItemClicked);



    // 设置按钮右键菜单策略
    ui->ptn_log->setContextMenuPolicy(Qt::CustomContextMenu);
    connect(ui->ptn_log, &QPushButton::customContextMenuRequested,
            this, &MainWindow::showLogContextMenu);


    // 新增：连接左键点击信号到新的槽函数
    connect(ui->ptn_log, &QPushButton::clicked,
            this, &MainWindow::openMessageControlDialog);

    // 新增：连接左键点击打开参数控制页面
    connect(ui->ptn_config, &QPushButton::clicked,
            this, &MainWindow::openConfigDialog);

    // 初始化界面
    //initNode();
    // 模拟发送20条消息数据
    // for (int i = 0; i < 20; ++i) {
    //     QString message = QString("[Alarm] Message %1").arg(i);
    //     // 模拟发送数据，直接调用 onDataReceived
    //     onDataReceived(message);


    //     // 随机选择消息等级进行模拟
    //     if (i % 3 == 0) {
    //         QString message = QString("[Warning] Message %1").arg(i);

    //         onDataReceived(message);
    //     } else if (i % 5 == 0) {
    //         QString message = QString("[Error] Message %1").arg(i);

    //         onDataReceived(message);
    //     }
    // }

    connect(ui->btn_minimize, &QPushButton::clicked, this, &MainWindow::on_btnMinimize_clicked);
    connect(ui->btn_maximize, &QPushButton::clicked, this, &MainWindow::on_btnMaximize_clicked);
    connect(ui->btn_close, &QPushButton::clicked, this, &MainWindow::on_btnClose_clicked);

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [=]() {
        QString current = QDateTime::currentDateTime().toString("yyyy 年 MM 月 d 日  HH:mm:ss");
        ui->lb_date->setText(current);
    });
    timer->start(1000); // 每秒更新时间
}
// 目前的任务是修改代码中的内容，使其适配模板2的内容
MainWindow::~MainWindow()
{
    std::cout << "[MainWindow] ~MainWindow()";
    DeviceManager::instance().clearAllNodes();

    delete ui;
}


//通信：关闭全部节点
void MainWindow::closeEvent(QCloseEvent* event)
{
    // 关闭窗口前先清除 DDS 资源DeviceManager::instance().removeNode(deviceName);

    for(int i=0;i<deviceIDList.size();++i)
    {
        DeviceManager::instance().removeNode(deviceIDList[i]);
        qDebug() << "deviceIDList[i]= "<<deviceIDList[i];
    }
    deviceIDList.clear();
    //QThread::sleep(5);
    //DeviceManager::instance().clearAllNodes();
    qDebug() << "[MainWindow] closeEvent() called";
    QMainWindow::closeEvent(event);
}


void MainWindow::on_btnMinimize_clicked()
{
    showMinimized();
}



void MainWindow::on_btnMaximize_clicked()
{
    if (isMaximized())
        showNormal();
    else
        showMaximized();
}

void MainWindow::on_btnClose_clicked()
{
    close();
}


void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton && ui->titleBarWidget->geometry().contains(event->pos())) {
        m_mousePressed = true;
        m_dragPos = event->globalPosition().toPoint() - frameGeometry().topLeft();
    }
}

void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (m_mousePressed && (event->buttons() & Qt::LeftButton)) {
        move(event->globalPosition().toPoint() - m_dragPos);
    }
}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    Q_UNUSED(event);
    m_mousePressed = false;
}

/**********************************************
* @file       mainwindow.cpp
* @brief      添加右键删除设备选项
* @author     yfk
* @date       2025-03-27
**********************************************/


void MainWindow::showContextMenu(const QPoint &pos)
{
    QTreeWidgetItem *item = ui->deviceTreeWidget->itemAt(pos);
    if (!item) return;

    // 不设置 currentItem，避免后续删除中断悬空引用
    QMenu contextMenu(this);
    QAction *deleteAction = contextMenu.addAction(tr("删除设备"));

    // 使用 lambda 捕获 item（删除后不再访问）
    connect(deleteAction, &QAction::triggered, this, [this, item]() {
        deleteDeviceItem(item);
    });

    contextMenu.exec(ui->deviceTreeWidget->viewport()->mapToGlobal(pos));
}

void MainWindow::deleteDeviceItem(QTreeWidgetItem *item)
{
    if (!item) return;

    QString deviceName = item->data(0, Qt::UserRole).toString();

    // 删除对应 tab
    for (int i = 0; i < ui->tabWidget_2->count(); ++i) {
        if (ui->tabWidget_2->tabText(i) == deviceName) {
            ui->tabWidget_2->removeTab(i);
            break;
        }
    }

    // 获取并处理自定义 widget
    QWidget *widget = ui->deviceTreeWidget->itemWidget(item, 0);
    if (widget) {
        ui->deviceTreeWidget->removeItemWidget(item, 0);
        widget->setParent(nullptr);
        widget->hide();
        widget->deleteLater();  // 延迟删除，防止事件中崩溃
    }

    // 从树中移除 item
    QTreeWidget *tree = ui->deviceTreeWidget;
    if (tree) {
        tree->clearSelection();
        tree->setCurrentItem(nullptr);

        int index = tree->indexOfTopLevelItem(item);
        if (index != -1) {
            tree->takeTopLevelItem(index);
        } else if (item->parent()) {
            item->parent()->removeChild(item);
        }
    }

    // 异步删除 QTreeWidgetItem
    QTimer::singleShot(0, this, [item]() {
        delete item;
    });
}


/**********************************************
* @file       mainwindow.cpp
* @brief      点击设置按钮，用于选择json文件
*             然后更新左侧设备列表，更新设备tab页
* @author     yfk
* @date       2025-02-11
**********************************************/

void MainWindow::on_pushButton_44_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "打开设备文件", "", "JSON Files (*.json)");

    if (fileName.isEmpty()) {
        return;
    }

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(this, "读取文件失败", "无法打开文件！");
        return;
    }

    QByteArray data = file.readAll();
    QJsonDocument doc = QJsonDocument::fromJson(data);

    if (!doc.isObject()) {
        QMessageBox::warning(this, "JSON 格式错误", "JSON 文件格式不正确！");
        return;
    }

    // 更新设备tab页
    readJsonAndUpdateTab(doc);

    // 更新设备树
    readJsonAndUpdateDevices(doc);
}

/**********************************************
* @file       mainwindow.cpp
* @brief      添加切换连接状态页面
* @author     yfk
* @date       2025-04-07
**********************************************/

void MainWindow::on_pushButton_47_clicked()
{
    qDebug() << "添加切换连接状态页面";
    // 创建 SwitchStaus 页面实例

    QString currentTabName = ui->tabWidget_2->tabText(ui->tabWidget_2->currentIndex());
    //qDebug()<<"on_pushButton_47_clicked(): = "<<currentTabName<<Qt::endl;

    SwitchStaus *SwitchStausPage = new SwitchStaus(currentTabName,this);
    //SwitchStaus *SwitchStausPage = new SwitchStaus(this);
    SwitchStausPage->setAttribute(Qt::WA_DeleteOnClose);
    // 连接信号和槽
    //connectSignalSlot();
    // 确保信号和槽连接在对话框显示之前
    //通信设置
    //QString dev = "ORS_Cask";
    QString dev = "ORS_"+currentTabName;
    //currentDevice = deviceinfo.deviceID;
    DeviceManager::instance().nodeFor(dev);
    auto node = DeviceManager::instance().nodeFor(dev);
    SwitchStausPage->attachToNode(node);


    //connect(SwitchStausPage, &SwitchStaus::colorChanged, this, &MainWindow::onColorChanged);
    //connect(SwitchStausPage,&SwitchStaus::upSubEvent,this,&MainWindow::upEventMsg);
    //connect(this,&MainWindow::initDeviceSwitch,SwitchStausPage,&SwitchStaus::initSwitch);
    // 显示页面
    SwitchStausPage->show();
    //emit initDeviceSwitch();
}
/**********************************************
* @file       mainwindow.cpp
* @brief      添加选择场景页面
* @author     yfk
* @date       2025-03-27
**********************************************/

void MainWindow::on_pushButton_48_clicked()
{
    qDebug() << " 添加选择场景页面";
    // 创建 SelectDevice 页面实例
    SelectDevice *selectDevicePage = new SelectDevice(this);

    // 显示选择设备页面
    selectDevicePage->show();  // 或者使用 exec() 如果想显示为模态窗口
}
/**********************************************
* @file       mainwindow.cpp
* @brief      在主界面中根据设备名称在设备列表中添加设备
* @author     yfk
* @date       2025-01-03
**********************************************/

void MainWindow::readJsonAndUpdateDevices(QJsonDocument &doc)
{

    QJsonObject root = doc.object();
    // qDebug() << " root : " << root;
    // 解析 deviceInfo 部分
    QJsonObject deviceInfo = root["DeviceInfo"].toObject();
    QString deviceName = deviceInfo["DeviceName"].toString();

    // qDebug() << " readJsonAndUpdateDevices: Device Name: " << deviceName;

    // 根据 deviceName 的不同值调用不同的处理函数
    // if (deviceName == "CMOR") {
    //     // 解析 functions 部分
    //     QJsonObject functions = root["FunctionInfo"].toObject();
    //     addCMORDeviceTolist(deviceName,functions);
    // } else if (deviceName == "Mover") {
    //     QJsonObject functions = root["FunctionInfo"].toObject();
    //     addMoverDeviceTolist(deviceName,functions);
    // } else if(deviceName == "Cask"){
    //     QJsonObject functions = root["FunctionInfo"].toObject();
    //     addCaskDeviceTolist(deviceName,functions);
    // }
    // else {
    //     //handleDefaultDevice(functions);
    // }
    //     // 解析 functions 部分
    QJsonObject functions = root["FunctionInfo"].toObject();
    addDeviceToList(deviceName);
}
/**********************************************
* @file       mainwindow.cpp
* @brief      主界面中用于解析json，然后在主界面中创建控制界面和状态显示界面的内容
* @author     yfk
* @date       2025-01-03
**********************************************/

void MainWindow::readJsonAndUpdateTab(QJsonDocument &doc)
{
    QJsonObject root = doc.object();

    // 解析 deviceInfo 部分
    QJsonObject deviceInfo = root["DeviceInfo"].toObject();
    QString deviceName = deviceInfo["DeviceName"].toString();
    // 根据 deviceName 的不同值调用不同的处理函数
    //    if (deviceName == "CMOR") {
    //        // 解析 functions 部分
    //        QJsonObject functions = root["FunctionInfo"].toObject();
    //        QJsonObject status = root["StatusInfo"].toObject();
    //        addCMORDeviceToTab(deviceName,functions,status);
    //    } else if (deviceName == "Mover") {
    //        // 解析 functions 部分
    //        QJsonObject functions = root["FunctionInfo"].toObject();
    // //       qDebug() << "  ----- functions:---- " << functions;
    //        QJsonObject status = root["StatusInfo"].toObject();

    //        addMoverDeviceToTab(deviceName,functions,status);

    //    } else if(deviceName == "Cask"){

    //        QJsonObject functions = root["FunctionInfo"].toObject();
    //        //       qDebug() << "  ----- functions:---- " << functions;
    //        QJsonObject status = root["StatusInfo"].toObject();
    //         // qDebug() << "  ----- status:---- " << status;
    //        addCaskDeviceToTab(deviceName,functions,status);
    //    }
    //    else if(deviceName == "Cask_2"){

    //        QJsonObject functions = root["FunctionInfo"].toObject();
    //        //       qDebug() << "  ----- functions:---- " << functions;
    //        QJsonObject status = root["StatusInfo"].toObject();
    //            // qDebug() << "  ----- status:---- " << status;
    //        addCask_2_DeviceToTab(deviceName,functions,status);
    //    }
    //    else if (deviceName == "111") {
    // //       // 解析 functions 部分
    // //       QJsonObject functions = root["FunctionInfo"].toObject();
    // //       QJsonObject status = root["StatusInfo"].toObject();
    // //       addMoverDeviceToTab(deviceName,functions,status);
    //    }
    //    else {
    //        //handleDefaultDevice(functions);
    //    }
    // 填充结构体数据
    deviceinfo.deviceName = deviceInfo["DeviceName"].toString();
    deviceinfo.deviceID = deviceInfo["DeviceID"].toString();
    deviceinfo.system = deviceInfo["System"].toString();
    deviceinfo.isRobot = deviceInfo["IsRobot"].toBool();
    deviceinfo.manufacturer = deviceInfo["Manufacturer"].toString();
    deviceinfo.serialNumber = deviceInfo["SerialNumber"].toString();
    QJsonObject functions = root["FunctionInfo"].toObject();
    QJsonObject status = root["StatusInfo"].toObject();
    addDeviceToTab(deviceName,functions,status);
    if(!deviceIDList.contains(deviceinfo.deviceID))
    {
        deviceIDList.append(deviceinfo.deviceID);
    }
}


void MainWindow::addDeviceToList(const QString &deviceName)
{
    // 1. 创建 Tree Item（父子层级等逻辑可扩展）
    QTreeWidgetItem *deviceItem = new QTreeWidgetItem(ui->deviceTreeWidget);

    // ⬅️ 绑定 deviceName 到该项（用于后续点击匹配 tab）
    deviceItem->setData(0, Qt::UserRole, deviceName);

    // 2. 构建自定义设备卡片
    QString statusText = "在线 · 需要维护";
    QString deviceID = QString("ID: %1").arg("CRN-01");
    QColor statusColor = QColor("#FFC107");  // 黄色状态点

    DeviceItemWidget *deviceWidget = new DeviceItemWidget(
        deviceName, statusText, deviceID, statusColor
        );

    // 3. 设置卡片为该 Item 的显示内容（仅列 0 有效）
    ui->deviceTreeWidget->setItemWidget(deviceItem, 0, deviceWidget);

    // 4. 设置项状态
    setDeviceActiveStatus(deviceItem, false);

    // 5. 设置当前项选中
    deviceItem->setSelected(true);
    ui->deviceTreeWidget->setCurrentItem(deviceItem);
}

QTreeWidgetItem* MainWindow::findDeviceItem(const QString &deviceName)
{
    QList<QTreeWidgetItem *> items = ui->deviceTreeWidget->findItems(deviceName, Qt::MatchExactly);
    if (!items.isEmpty()) {
        return items.first();  // 返回找到的设备项
    }
    return nullptr;  // 如果没有找到设备项，返回 nullptr
}

void MainWindow::addCMORDeviceTolist(QString deviceName, QJsonObject &functions)
{
    // 添加设备信息到树形控件
    addDeviceToList(deviceName);
    //qDebug() << "Functions Parsed:" << functions; // 输出 functions 部分，检查是否正确解析

    for (auto it = functions.begin(); it != functions.end(); ++it) {
        QString functionName = it.key();
        QJsonObject functionDetails = it.value().toObject();
       //qDebug() << "Function Name: " << functionName;
       // qDebug() << "Function Details: " << functionDetails;

        // 添加关节信息到设备项下
        if(functionName =="moveJoint")
            /* 传进去的json内容  Function Details:
             *  QJsonObject({
             * "joint_1":{"default":"0","max":"180","min":"-180"},
                "joint_2":{"default":"0","max":"180","min":"-180"},
                "joint_3":{"default":"0","max":"180","min":"-180"},
                "uiElement":"slider"})
            */
        {
            functionDetails = functionDetails["Parameters"].toObject();
            addJointsToDevice(deviceName, functionDetails);

        }

    }
}

void MainWindow::addMoverDeviceTolist(QString deviceName, QJsonObject &functions)
{
    // 添加设备信息到树形控件
    addDeviceToList(deviceName);
}

void MainWindow::addCaskDeviceTolist(QString deviceName, QJsonObject &functions)
{
    // 添加设备信息到树形控件
    addDeviceToList(deviceName);
}

void MainWindow::addCMORDeviceToTab(QString deviceName, QJsonObject &functions, QJsonObject &status)
{
    qDebug() << " addCMORDeviceToTab: functions: " << functions;
    // 创建一个新的 Tab 页
    QWidget *deviceInfoTab = new QWidget();
    QHBoxLayout *deviceLayout = new QHBoxLayout(deviceInfoTab);
    // 移除布局的边距和间距，确保控件填充无缝
    deviceLayout->setContentsMargins(0, 0, 0, 0);

    // 创建一个 QScrollArea 用于显示功能控件
    QScrollArea *functionScrollArea = new QScrollArea(deviceInfoTab);
    QWidget *functionContentWidget = new QWidget();
    QVBoxLayout *functionLayout = new QVBoxLayout(functionContentWidget);

    // 设置 functionScrollArea
    functionScrollArea->setWidget(functionContentWidget);
    functionScrollArea->setWidgetResizable(true);
    functionScrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    functionScrollArea->setStyleSheet("QScrollArea { border: none; margin: 0; padding: 0; }");
    // 禁用横向滚动条
    //functionScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 创建另一个 QScrollArea 用于显示状态信息
    QScrollArea *statusScrollArea = new QScrollArea(deviceInfoTab);
    QWidget *statusContentWidget = new QWidget();
    QVBoxLayout *statusLayout = new QVBoxLayout(statusContentWidget);

    // 设置 statusScrollArea
    statusScrollArea->setWidget(statusContentWidget);
    statusScrollArea->setWidgetResizable(true);
    statusScrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    statusScrollArea->setStyleSheet("QScrollArea { border: none; margin: 0; padding: 0; }");
    // 禁用横向滚动条
    //statusScrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    // 填充 statusContentWidget 中的内容
    JointStatusWidget* jointStatusWidget = new JointStatusWidget(status, statusContentWidget);
    connect(jointStatusWidget,&JointStatusWidget::upSubEvent,this,&MainWindow::upEventMsg);//接收事件消息

    // 填充 functionContentWidget 中的内容
       for (auto it = functions.begin(); it != functions.end(); ++it) {
           QString functionName = it.key();
           QJsonObject functionDetails = it.value().toObject();

           if (functionName == "moveJoint") {
               // 创建 moveJoint 控件
               functionDetails = functionDetails["Parameters"].toObject();
               MoveJoint *movejointwidget = new MoveJoint(functionName,functionDetails,functionContentWidget);
               functionLayout->addWidget(movejointwidget);
           } else if (functionName == "moveTool") {
               // 创建 moveTool 控件
               MoveTool *movetoolwidget = new MoveTool(functionName,functionDetails,functionContentWidget);
               functionLayout->addWidget(movetoolwidget);
           }
       }


    QJsonObject Parameters = status["Parameters"].toObject();
    QJsonObject TcpToolPosition = Parameters["endToolPosition"].toObject();
    qDebug() << "---" <<  TcpToolPosition << "---"<< Qt::endl;
    TcpStatusWidget* tcpStatusWidget = new TcpStatusWidget(TcpToolPosition,statusContentWidget);

    // 将状态信息组框添加到布局中
    statusLayout->addWidget(jointStatusWidget);
    statusLayout->addWidget(tcpStatusWidget);


    // 填充 statusContentWidget 中的内容
    // 此处根据实际需要动态填充 statusLayout 的内容

    // 将两个 ScrollArea 添加到布局中
    deviceLayout->addWidget(functionScrollArea, 1);  // 占据1倍权重
    deviceLayout->addWidget(statusScrollArea, 1);   // 占据1倍权重

    // 设置 Tab 页的布局
    deviceInfoTab->setLayout(deviceLayout);

    // 将 Tab 页添加到 tabWidget_2
    ui->tabWidget_2->addTab(deviceInfoTab, deviceName);
    ui->tabWidget_2->setCurrentWidget(deviceInfoTab);
}

void MainWindow::addMoverDeviceToTab(QString deviceName, QJsonObject &functions, QJsonObject &status)
{
   // qDebug() << " addMoverDeviceToTab: functions: " << functions;

   // qDebug() << " ----addMoverDeviceToTab: functions:---- ";
    QWidget *deviceInfoTab = new QWidget();
    QHBoxLayout *deviceLayout = new QHBoxLayout(deviceInfoTab);
    deviceLayout->setContentsMargins(0, 0, 0, 0);

    // 创建一个 QScrollArea 用于显示功能控件
    QScrollArea *functionScrollArea = new QScrollArea(deviceInfoTab);
    QWidget *functionContentWidget = new QWidget();
    QVBoxLayout *functionLayout = new QVBoxLayout(functionContentWidget);

    // 设置 functionScrollArea
    functionScrollArea->setWidget(functionContentWidget);
    functionScrollArea->setWidgetResizable(true);
    functionScrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    functionScrollArea->setStyleSheet("QScrollArea { border: none; margin: 0; padding: 0; }");


    // 创建另一个 QScrollArea 用于显示状态信息
    QScrollArea *statusScrollArea = new QScrollArea(deviceInfoTab);
    QWidget *statusContentWidget = new QWidget();
    QVBoxLayout *statusLayout = new QVBoxLayout(statusContentWidget);

    // 设置 statusScrollArea
    statusScrollArea->setWidget(statusContentWidget);
    statusScrollArea->setWidgetResizable(true);
    statusScrollArea->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    statusScrollArea->setStyleSheet("QScrollArea { border: none; margin: 0; padding: 0; }");

    // 填充 functionContentWidget 中的内容
    for (auto it = functions.begin(); it != functions.end(); ++it) {
        QString functionName = it.key();
        QJsonObject functionDetails = it.value().toObject();
        //qDebug() << "functionName:"<< functionName << endl;
        if (functionName == "Control") {
            // 创建 QGroupBox 用于包装功能控件
            QGroupBox *functionGroupBox = new QGroupBox(functionName, functionContentWidget);
            QVBoxLayout *groupBoxLayout = new QVBoxLayout(functionGroupBox);
            // 设置QGroupBox的布局
            for(auto i = functionDetails.begin(); i != functionDetails.end(); ++i)
            {
                QString  groupboxName = i.key();
                QJsonObject groupboxDetatils = i.value().toObject();
                //qDebug() << "groupboxDetatils:"<< groupboxDetatils << endl;
               // qDebug() << "groupboxName:"<< groupboxName << endl;
                if(groupboxName == "Modelcontrol")
                {
                    QJsonObject ModelDetails = groupboxDetatils;
                    //qDebug() << "ModelDetails:"<< ModelDetails << endl;
                    // 传进去的是  QJsonObject({"Parameters":{"radiobutton":["Sync","moverUp","moverDown"]}})
                    ModelControl *modelControlwidget = new ModelControl(groupboxName,ModelDetails,functionGroupBox);
                    // 将控件添加到 groupBoxLayout
                    groupBoxLayout->addWidget(modelControlwidget);
                }
                else if(groupboxName == "Liftcontrol")
                {
                     QJsonObject ModelDetails = groupboxDetatils;
                     LiftControl *LiftControlwidget = new LiftControl(groupboxName,ModelDetails,functionGroupBox);
                     groupBoxLayout->addWidget(LiftControlwidget);
                }
                else if(groupboxName == "Pivot_pincontrol")
                {
                     QJsonObject ModelDetails = groupboxDetatils;
                     PinControl *PinControlwidget = new PinControl(groupboxName,ModelDetails,functionGroupBox);
                     groupBoxLayout->addWidget(PinControlwidget);
                }else if(groupboxName == "Singlestepcontrol")
                {
                     QJsonObject ModelDetails = groupboxDetatils;
                     SingleStepControl *SingleStepControlwidget = new SingleStepControl(groupboxName,ModelDetails,functionGroupBox);
                     groupBoxLayout->addWidget(SingleStepControlwidget);
                }else if(groupboxName == "Multistepcontrol")
                {
                    QJsonObject ModelDetails = groupboxDetatils;
                    MultiStepControl *MultiStepControlwidget = new MultiStepControl(groupboxName,ModelDetails,functionGroupBox);
                    groupBoxLayout->addWidget(MultiStepControlwidget);
                }

            }
            // 将 functionGroupBox 添加到 functionContentWidget
            functionContentWidget->layout()->addWidget(functionGroupBox);
        }
        else if (functionName == "SetParameters") {
            // 创建 QGroupBox 用于包装功能控件
            QGroupBox *functionGroupBox = new QGroupBox(functionName, functionContentWidget);
            QVBoxLayout *groupBoxLayout = new QVBoxLayout(functionGroupBox);
            for(auto i = functionDetails.begin(); i != functionDetails.end(); ++i)
            {
                QString  groupboxName = i.key();
                QJsonObject groupboxDetatils = i.value().toObject();
                if(groupboxName == "overall")
                {
                    QJsonObject ModelDetails = groupboxDetatils;
                    Overall *Overallwidget = new Overall(groupboxName,ModelDetails,functionGroupBox);
                    // 将控件添加到 groupBoxLayout
                    groupBoxLayout->addWidget(Overallwidget);
                }
                else if(groupboxName == "MoverUp")
                {
                     QJsonObject ModelDetails = groupboxDetatils;
                     MoverUp *MoverUpwidget = new MoverUp(groupboxName,ModelDetails,functionGroupBox);
                     groupBoxLayout->addWidget(MoverUpwidget);
                }
                else if(groupboxName == "MoverDown")
                {
                    QJsonObject ModelDetails = groupboxDetatils;
                    MoverDown *MoverDownwidget = new MoverDown(groupboxName,ModelDetails,functionGroupBox);
                    groupBoxLayout->addWidget(MoverDownwidget);
                }
            }
            functionContentWidget->layout()->addWidget(functionGroupBox);
        }
    }

    // 填充 statusContentWidget 中的内容
    status = status["Parameters"].toObject();
    // 创建 QGroupBox 用于包装功能控件

    QGroupBox *statusGroupBox = new QGroupBox("status", statusContentWidget);
    QVBoxLayout *statusgroupBoxLayout = new QVBoxLayout(statusGroupBox);
    statusLayout->addWidget(statusGroupBox);

    for (auto it = status.begin(); it != status.end(); ++it) {
        QString statusName = it.key();
        QJsonObject statusDetails = it.value().toObject();
        if(statusName == "MoverUp")
        {
            QJsonObject ModelDetails = statusDetails;
            MoverUpStatus *MoverUpwidget = new MoverUpStatus(statusName,ModelDetails,statusGroupBox);
            // 将控件添加到 groupBoxLayout
            statusgroupBoxLayout->addWidget(MoverUpwidget);
        }
        else if(statusName == "MoverDown")
        {
            QJsonObject ModelDetails = statusDetails;
            MoverDownStatus *MoverDownwidget = new MoverDownStatus(statusName,ModelDetails,statusGroupBox);
            // 将控件添加到 groupBoxLayout
            statusgroupBoxLayout->addWidget(MoverDownwidget);
        }
    }

    deviceLayout->addWidget(functionScrollArea, 1);  // 占据1倍权重
    deviceLayout->addWidget(statusScrollArea, 1);   // 占据1倍权重

    // 设置 Tab 页的布局
    deviceInfoTab->setLayout(deviceLayout);

    // 将 Tab 页添加到 tabWidget_2
    ui->tabWidget_2->addTab(deviceInfoTab, deviceName);
}

void MainWindow::addCaskDeviceToTab(QString deviceName, QJsonObject &functions, QJsonObject &status)
{
    QWidget *deviceInfoTab = new QWidget();
    QHBoxLayout *deviceLayout = new QHBoxLayout(deviceInfoTab);
    deviceLayout->setContentsMargins(0, 0, 0, 0);

    // 创建一个 QScrollArea 用于显示功能控件
    QScrollArea *functionScrollArea = new QScrollArea(deviceInfoTab);
    QWidget *functionContentWidget = new QWidget();
    QVBoxLayout *functionLayout = new QVBoxLayout(functionContentWidget);

    // 设置 functionScrollArea
    functionScrollArea->setWidget(functionContentWidget);
    functionScrollArea->setWidgetResizable(true);
    functionScrollArea->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    functionScrollArea->setStyleSheet("QScrollArea { border: none; margin: 0; padding: 0; }");


    // 填充 functionContentWidget 中的内容
    for (auto it = functions.begin(); it != functions.end(); ++it) {
        QString functionName = it.key();
        QJsonObject functionDetails = it.value().toObject();
        //qDebug() << "functionName:"<< functionName << endl;
        if (functionName == "Move") {
            QJsonObject ModelDetails = functionDetails;
            qDebug() << "ModelDetails:"<< ModelDetails << Qt::endl;
            // 传进去的是  QJsonObject({"Parameters":{"radiobutton":["Sync","moverUp","moverDown"]}})
            CaskMoveControl *CaskMoveControlwidget = new CaskMoveControl(functionName,ModelDetails,deviceinfo.deviceID,functionContentWidget);
            // 将控件添加到 functionLayout
            functionLayout->addWidget(CaskMoveControlwidget);
            // CaskMoveControl *CaskMoveControlwidget2 = new CaskMoveControl(functionName,ModelDetails,functionContentWidget);
            // functionLayout->addWidget(CaskMoveControlwidget2);


        }
        else if (functionName == "Stop1") {
            QJsonObject ModelDetails = functionDetails;
            qDebug() << "ModelDetails:"<< ModelDetails << Qt::endl;
            // 传进去的是  QJsonObject({"Parameters":{"radiobutton":["Sync","moverUp","moverDown"]}})
            CaskStopControl *CaskStopControlwidget = new CaskStopControl(functionName,ModelDetails,functionContentWidget);
            // 将控件添加到 functionLayout
            functionLayout->addWidget(CaskStopControlwidget);

            // CaskStopControl *CaskStopControlwidget2 = new CaskStopControl(functionName,ModelDetails,functionContentWidget);
            // functionLayout->addWidget(CaskStopControlwidget2);
        }
    }


    // 创建另一个 QScrollArea 用于显示状态信息
    QScrollArea *statusScrollArea = new QScrollArea(deviceInfoTab);
    QWidget *statusContentWidget = new QWidget();
    QVBoxLayout *statusLayout = new QVBoxLayout(statusContentWidget);

    // 设置 statusScrollArea
    statusScrollArea->setWidget(statusContentWidget);
    statusScrollArea->setWidgetResizable(true);
    statusScrollArea->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    statusScrollArea->setStyleSheet("QScrollArea { border: none; margin: 0; padding: 0; }");

    // 直接将 CaskStatusWidget 添加到 deviceLayout 中
    // qDebug() << "status:"<< status << Qt::endl;
    status = status["Parameters"].toObject();
    CaskStatus *CaskStatusWidget = new CaskStatus(status,deviceinfo.deviceID, statusContentWidget);
    statusLayout->addWidget(CaskStatusWidget); // 将状态信息控件添加到 statusLayout
    // 设置 Tab 页的布局
    deviceLayout->addWidget(functionScrollArea);
    deviceLayout->addWidget(statusScrollArea);
    deviceInfoTab->setLayout(deviceLayout);

    // 将 Tab 页添加到 tabWidget_2
    ui->tabWidget_2->addTab(deviceInfoTab, deviceName);
    ui->tabWidget_2->setCurrentWidget(deviceInfoTab);

    // //通信设置
    // QString dev = "ORS_Cask";
    // currentDevice = dev;
    // DeviceManager::instance().nodeFor(dev);
    // auto node = DeviceManager::instance().nodeFor(currentDevice);
    // CaskStatusWidget->attachToNode(node);

    connect(CaskStatusWidget,&CaskStatus::upSubEvent,this,&MainWindow::upEventMsg);
}
/**********************************************
* @file       mainwindow.cpp
* @brief      添加小绿点操作
* @author     yfk
* @date       2025-03-28
**********************************************/

void MainWindow::setDeviceActiveStatus(QTreeWidgetItem *item, bool isActive, const QString &color)
{
    if (!item) return;

    // 拿到之前 setItemWidget 的小部件
    auto *widget = qobject_cast<DeviceItemWidget*>(
        ui->deviceTreeWidget->itemWidget(item, 0));
    if (!widget) return;

    // ① 亮/灭外框
    widget->setActive(isActive);

    // ② 改圆点颜色
    QColor dotColor = Qt::gray;
    if (color == "green")
    {
        dotColor = Qt::green;
        widget->setStatusText(u8"command");
    }
    else if (color == "yellow")
    {
        dotColor = Qt::yellow;
        widget->setStatusText(u8"halt");
    }
    else if (color == "red")
    {
        dotColor = Qt::red;
    }
    widget->setStatusColor(dotColor);
    widget->setStatusText(u8"off");
}

/**********************************************
* @file       mainwindow.cpp
* @brief      只保留一个小绿点操作
* @author     yfk
* @date       2025-03-28
**********************************************/

void MainWindow::updateActiveDeviceStatus(QTreeWidgetItem *selectedItem)
{
    int deviceCount = ui->deviceTreeWidget->topLevelItemCount();

    // 遍历所有设备，移除绿点
    for (int i = 0; i < deviceCount; ++i) {
        QTreeWidgetItem *item = ui->deviceTreeWidget->topLevelItem(i);
        if (item) {
            setDeviceActiveStatus(item, false, "gray");  // 清除所有设备的颜色，默认颜色为灰色
        }
    }

    // 只给当前选中的设备添加绿点
    if (selectedItem) {
        setDeviceActiveStatus(selectedItem, true, "gray");  // 默认设置灰色
    }
}

void MainWindow::addDeviceToTab(QString deviceName, QJsonObject &functions, QJsonObject &status)
{
    QWidget *deviceInfoTab = new QWidget();
    QHBoxLayout *deviceLayout = new QHBoxLayout(deviceInfoTab);
    deviceLayout->setContentsMargins(0, 0, 0, 0);

    // functionScrollArea 用于左侧显示功能控件
    QScrollArea *functionScrollArea = new QScrollArea(deviceInfoTab);
    QWidget *functionContentWidget = new QWidget();
    QVBoxLayout *functionLayout = new QVBoxLayout(functionContentWidget);
    functionLayout->setContentsMargins(4, 6, 4, 6); //(left, top, right, bottom)

    // 设置 functionScrollArea
    functionScrollArea->setWidget(functionContentWidget);
    functionScrollArea->setWidgetResizable(true);
    functionScrollArea->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    functionScrollArea->setStyleSheet("QScrollArea { border: none; margin: 0; padding: 0; }");

    // 填充 functionContentWidget 中的内容
    for (auto it = functions.begin(); it != functions.end(); ++it) {
        QString functionlayout = it.key();
        QJsonObject functionDetails = it.value().toObject();
        //qDebug() << "functionName:"<< functionName << endl;
        qDebug() << "now deviceName = :"<< deviceinfo.deviceID << Qt::endl;
        if (functionlayout == "Lab_Le_Lab_Ptn_Ptn") {
            QJsonObject ModelDetails = functionDetails;
            QString functionName = ModelDetails["GroupboxName"].toString();
            CaskMoveControl *CaskMoveControlwidget = new CaskMoveControl(functionName,ModelDetails,deviceinfo.deviceID,functionContentWidget);

            // 建立哈希映射
            functionNameToWidgetMap.insert(functionName, CaskMoveControlwidget);
            functionLayout->addWidget(CaskMoveControlwidget);
            //通信设置
            //8.01
            currentDevice = deviceinfo.deviceID;
            DeviceManager::instance().nodeFor(deviceinfo.deviceID);
            auto node = DeviceManager::instance().nodeFor(currentDevice);
            CaskMoveControlwidget->attachToNode(node);


        }
        if (functionlayout == "Lab_Le_Lab_Ptn_Ptn2") {
            QJsonObject ModelDetails = functionDetails;
            QString functionName = ModelDetails["GroupboxName"].toString();

            CaskMoveControl *CaskMoveControlwidget = new CaskMoveControl(functionName,ModelDetails,deviceinfo.deviceID,functionContentWidget);
            // 建立哈希映射
            functionNameToWidgetMap.insert(functionName, CaskMoveControlwidget);
            functionLayout->addWidget(CaskMoveControlwidget);
            //通信设置
            //8.01
            currentDevice = deviceinfo.deviceID;
            DeviceManager::instance().nodeFor(deviceinfo.deviceID);
            auto node = DeviceManager::instance().nodeFor(currentDevice);
            CaskMoveControlwidget->attachToNode(node);
        }
        if (functionlayout == "lab_le_lab_ptn_ptn3") {
            QJsonObject ModelDetails = functionDetails;
            QString functionName = ModelDetails["GroupboxName"].toString();
            CaskMoveControl *CaskMoveControlwidget = new CaskMoveControl(functionName,ModelDetails,deviceinfo.deviceID,functionContentWidget);
            // 建立哈希映射
            functionNameToWidgetMap.insert(functionName, CaskMoveControlwidget);
            functionLayout->addWidget(CaskMoveControlwidget);
            //通信设置
            //8.01
            currentDevice = deviceinfo.deviceID;
            DeviceManager::instance().nodeFor(deviceinfo.deviceID);
            auto node = DeviceManager::instance().nodeFor(currentDevice);
            CaskMoveControlwidget->attachToNode(node);
        }
        if(functionlayout == "lab_le_lab_ptn_ptn4")
        {
            QJsonObject ModelDetails = functionDetails;
            QString functionName = ModelDetails["GroupboxName"].toString();

            CaskMoveControl *CaskMoveControlwidget = new CaskMoveControl(functionName,ModelDetails,deviceinfo.deviceID,functionContentWidget);
            // 建立哈希映射
            functionNameToWidgetMap.insert(functionName, CaskMoveControlwidget);
            functionLayout->addWidget(CaskMoveControlwidget);
            //通信设置
            //8.01
            currentDevice = deviceinfo.deviceID;
            DeviceManager::instance().nodeFor(deviceinfo.deviceID);
            auto node = DeviceManager::instance().nodeFor(currentDevice);
            CaskMoveControlwidget->attachToNode(node);
        }
    }


    // statusScrollArea 用于右侧显示状态信息
    QScrollArea *statusScrollArea = new QScrollArea(deviceInfoTab);
    QWidget *statusContentWidget = new QWidget();
    QVBoxLayout *statusLayout = new QVBoxLayout(statusContentWidget);
    statusLayout->setContentsMargins(4, 6, 4, 6); //(left, top, right, bottom)

    // 设置 statusScrollArea
    statusScrollArea->setWidget(statusContentWidget);
    statusScrollArea->setWidgetResizable(true);
    statusScrollArea->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    statusScrollArea->setStyleSheet("QScrollArea { border: none; margin: 0; padding: 0; }");

    status = status["Parameters"].toObject();
    CaskStatus *CaskStatusWidget = new CaskStatus(status, deviceinfo.deviceID,statusContentWidget);
    statusLayout->addWidget(CaskStatusWidget); // 将状态信息控件添加到 statusLayout
    //通信设置//8.01
    currentDevice = deviceinfo.deviceID;
    DeviceManager::instance().nodeFor(deviceinfo.deviceID);
    auto node = DeviceManager::instance().nodeFor(currentDevice);
    CaskStatusWidget->attachToNode(node);

    // 设置 Tab 页的布局
    deviceLayout->addWidget(functionScrollArea);
    deviceLayout->addWidget(statusScrollArea);
    deviceInfoTab->setLayout(deviceLayout);

    // 将 Tab 页添加到 tabWidget_2
    ui->tabWidget_2->addTab(deviceInfoTab, deviceName);
    ui->tabWidget_2->setCurrentWidget(deviceInfoTab);

    connect(CaskStatusWidget,&CaskStatus::upSubEvent,this,&MainWindow::upEventMsg);//接收事件消息
    connect(CaskStatusWidget, &CaskStatus::colorChanged, this, &MainWindow::onColorChanged);
}


void MainWindow::onDeviceTreeItemClicked(QTreeWidgetItem *item, int column)
{
    QString tabName = item->data(0, Qt::UserRole).toString();
    qDebug() << "点击设备项：" << tabName;

    // 遍历 tab，切换到匹配名称
    for (int i = 0; i < ui->tabWidget_2->count(); ++i) {
        if (ui->tabWidget_2->tabText(i) == tabName) {
            ui->tabWidget_2->setCurrentIndex(i);
            return;
        }
    }

    qDebug() << "未找到匹配 tab：" << tabName;
}
/**********************************************
* @file       mainwindow.cpp
* @brief      解析json用于实现左侧设备列表添加设备
* @author     yfk
* @date       2025-01-03
**********************************************/

void MainWindow::addJointsToDevice(const QString &deviceName, const QJsonObject &functionDetails)
{
    //qDebug() << "functionDetails:" << functionDetails;  // 打印出完整的 functionDetails
    // 查找树形控件中的设备项
    QTreeWidgetItem *deviceItem = findDeviceItem(deviceName);
    if (deviceItem) {
        for (auto it = functionDetails.begin(); it != functionDetails.end(); ++it) {
            QString JointName = it.key();
            QJsonObject JointDetails = it.value().toObject();
            //qDebug() << "JointName Name: " << JointName;
           // qDebug() << "Joint Details: " << JointDetails;
            if(JointName != "uiElement"){
                QTreeWidgetItem *jointItem = new QTreeWidgetItem(deviceItem);
                jointItem->setText(0, JointName);  // 设置关节名称
            }
        }
    }
}

// void MainWindow::connectSignalSlot()
// {
//     // 创建 SwitchStaus 对象
//     switchStaus = new SwitchStaus(this);

//     // 连接 SwitchStaus 的 colorChanged 信号到 MainWindow 的槽函数
//     if (connect(switchStaus, &SwitchStaus::colorChanged, this, &MainWindow::onColorChanged)) {
//         qDebug() << "Signal-slot connected successfully!";
//     } else {
//         qDebug() << "Signal-slot connection failed!";
//     }
// }

void MainWindow::onColorChanged(const QString &color)
{
    //qDebug() << "Received color change signal with color: " << color;  // 确保信号到达槽函数

    // 获取当前选中的设备
    QTreeWidgetItem *selectedItem = ui->deviceTreeWidget->currentItem();

    if (selectedItem) {
        //qDebug() << "Selected item: " << selectedItem->text(0); // 打印选中的设备项名称
        setDeviceActiveStatus(selectedItem, true, color);  // 更新设备的颜色
    } else {
        qDebug() << "No item selected!";
    }
}

void MainWindow::onDataReceived(const QString &message)
{
    // 从消息中提取等级（例如：fatal、Warning、Error）
    QString level = "fatal";  // 默认等级
    if (message.contains("[warning]")) {
        level = "Warning";
    } else if (message.contains("[Error]")) {
        level = "Error";
    }

    // 调用 appendMessage 来更新 QTextBrowser 内容并显示不同颜色
    appendMessage(message, level);
}

void MainWindow::appendMessage(const QString &message, const QString &level)
{
    QString content = message.section(' ', 2);  // 提取正文
    MessageItemWidget *msg = new MessageItemWidget(level, content);

    QVBoxLayout *containerLayout = qobject_cast<QVBoxLayout*>(ui->warningContentWidget->layout());
    if (!containerLayout) {
        containerLayout = new QVBoxLayout(ui->warningContentWidget);
        containerLayout->setContentsMargins(8, 8, 8, 8);
        containerLayout->setSpacing(6);
    }

    containerLayout->addWidget(msg);

    QScrollBar *vbar = ui->warning_scrollArea->verticalScrollBar();
    if (vbar)
        vbar->setValue(vbar->maximum());
}

void MainWindow::showLogContextMenu(const QPoint &pos)
{
    // QMenu contextMenu(tr("Log Menu"), this);

    // QAction *clearAlarmAction = new QAction(tr("清空报警信息"), this);
    // QAction *clearMessageAction = new QAction(tr("清空消息信息"), this);
    // QAction *exportAlarmAction = new QAction(tr("导出报警信息"), this);
    // QAction *exportMessageAction = new QAction(tr("导出消息信息"), this);

    // contextMenu.addAction(clearAlarmAction);
    // contextMenu.addAction(clearMessageAction);
    // contextMenu.addSeparator();
    // contextMenu.addAction(exportAlarmAction);
    // contextMenu.addAction(exportMessageAction);

    // connect(clearAlarmAction, &QAction::triggered, this, [this]() {
    //     ui->text_warning->clear();
    // });

    // connect(clearMessageAction, &QAction::triggered, this, [this]() {
    //     ui->text_message->clear();
    // });

    // connect(exportAlarmAction, &QAction::triggered, this, [this]() {
    //     exportTextBrowserContent(ui->text_warning, "报警信息导出.txt");
    // });

    // connect(exportMessageAction, &QAction::triggered, this, [this]() {
    //     exportTextBrowserContent(ui->text_message, "消息信息导出.txt");
    // });

    // contextMenu.exec(ui->ptn_log->mapToGlobal(pos));
}

void MainWindow::exportTextBrowserContent(QTextBrowser* browser, const QString& defaultFileName)
{
    QString fileName = QFileDialog::getSaveFileName(this, "导出日志信息", defaultFileName, "Text Files (*.txt)");
    if (!fileName.isEmpty()) {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QTextStream out(&file);
            out << browser->toPlainText();
            file.close();
            QMessageBox::information(this, "导出成功", "日志信息已成功导出！");
        } else {
            QMessageBox::warning(this, "导出失败", "无法写入文件！");
        }
    }
}

void MainWindow::openMessageControlDialog()
{
    MessageControl *msgDialog = new MessageControl(this);  // 创建对话框

    // ✅ 连接清空与导出信号
    connect(msgDialog, &MessageControl::clearAlarm, this, [this]() {
        clearMessageItems(ui->warningContentWidget);
    });

    connect(msgDialog, &MessageControl::clearMessage, this, [this]() {
        clearMessageItems(ui->messageContentWidget);
    });

    connect(msgDialog, &MessageControl::exportAlarm, this, [this]() {
        QString fileName = QFileDialog::getSaveFileName(
            this,
            "导出报警信息",
            QStandardPaths::writableLocation(QStandardPaths::DesktopLocation) + "/报警信息导出.txt",
            "文本文件 (*.txt)"
            );

        if (!fileName.isEmpty()) {
            exportContent(ui->warningContentWidget, fileName);
        }
    });


    connect(msgDialog, &MessageControl::exportMessage, this, [this]() {
        exportContent(ui->messageContentWidget, "消息信息导出.txt");
    });

    // // ✅ 连接 comboBox 信号：根据类型执行响应
    // connect(msgDialog, &MessageControl::messageTypeChanged,
    //         this, [this](const QString &type) {
    //             if (type == "Alarm") {
    //                 qDebug() << "选择了 Alarm";
    //                 // 你可以在这里添加只显示报警信息的逻辑
    //             } else if (type == "Worning") {
    //                 qDebug() << "选择了 Worning";
    //                 // 显示警告信息
    //             } else if (type == "Error") {
    //                 qDebug() << "选择了 Error";
    //                 // 显示错误信息
    //             }else if (type == "All") {
    //                 qDebug() << "选择了 All";
    //                 // 显示错误信息
    //             }
    //         });

    connect(msgDialog, &MessageControl::messageFiltersChanged,
            this, [this](const QStringList &filters) {
                qDebug() << "当前勾选：" << filters;

                // 示例：你可以根据 filters 来决定是否隐藏/过滤 QTextBrowser 内容
                // if (filters.contains("Alarm")) { ... }
            });

    msgDialog->exec();  // 弹出对话框
}

void MainWindow::clearMessageItems(QWidget *container) {
    QLayout *layout = container->layout();
    if (!layout) return;
    qDebug() << "删除消息：";

    while (QLayoutItem *item = layout->takeAt(0)) {
        if (QWidget *widget = item->widget()) {
            widget->deleteLater(); // 安全删除
        }
        delete item;
    }
}

void MainWindow::exportContent(QWidget *container, const QString &filename) {
    QLayout *layout = container->layout();
    if (!layout) return;
    qDebug() << "导出消息：";
    QFile file(filename);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return;
    QTextStream out(&file);

    for (int i = 0; i < layout->count(); ++i) {
        QWidget *widget = layout->itemAt(i)->widget();
        if (MessageItemWidget *item = qobject_cast<MessageItemWidget *>(widget)) {
            out << item->getText() << "\n";
        }
    }
}

void MainWindow::openConfigDialog()
{
    // 创建 QJsonObject 并设置 Movejoint 的配置
    QJsonObject movejointConfig;
    movejointConfig["joint_1"] = QJsonObject{{"min", 0}, {"max", 180}, {"default", 80}};
    movejointConfig["joint_2"] = QJsonObject{{"min", 0}, {"max", 180}, {"default", 80}};
    movejointConfig["joint_3"] = QJsonObject{{"min", 0}, {"max", 180}, {"default", 80}};
    movejointConfig["joint_4"] = QJsonObject{{"min", 0}, {"max", 180}, {"default", 80}};
    movejointConfig["joint_5"] = QJsonObject{{"min", 0}, {"max", 180}, {"default", 80}};
    movejointConfig["joint_6"] = QJsonObject{{"min", 0}, {"max", 180}, {"default", 80}};

    // 创建配置数据并将 Movejoint 配置添加进去
    QJsonObject configData;
    configData["movejoint"] = movejointConfig;
    configData["MoveTool"] = "value2";  // 可以根据需要设置其他键值

    // 创建并打开配置对话框
    ConfigDialog *cfgDialog = new ConfigDialog(this);

    // 将数据传递给 ConfigDialog 页面
    cfgDialog->loadConfigData(configData);

    // ✅ 连接信号和槽
    connect(cfgDialog, &ConfigDialog::updateFlag3ControlSignal,
            this, &MainWindow::onUpdateFlag3ControlReceived);

    cfgDialog->exec();  // 弹出对话框


}

void MainWindow::onUpdateFlag3ControlReceived(const QJsonObject &jsonData)
{
    QString targetFunctionName = "MoveJoint";

    if (functionNameToWidgetMap.contains(targetFunctionName)) {
        CaskMoveControl *targetWidget = functionNameToWidgetMap.value(targetFunctionName);

        // 现在你拿到了对应的 CaskMoveControl，可以调用它的方法
        // 例如你可以定义一个更新方法 updateFromJson(jsonData)
        targetWidget->updateFlag3ControlSlot(jsonData);
        // targetWidget->getFlag3Angles();

        qDebug() << "Updated CaskMoveControl for" << targetFunctionName;
    } else {
        qDebug() << "No CaskMoveControl found for" << targetFunctionName;
    }
}

// void MainWindow::on_pusherbutton_clicked()
// {

//     uint32_t domainId = 0; // 或从UI/配置获取
//     QString pubName = "ORS_CMOR/Device02"; // 固定话题
//     QString subName = "ORS_CMOR"; // 固定话题
//     QString f_deviceID = "ORS_CMOR";
//     createAndSubscribeNewNode(domainId,f_deviceID);
//     std::this_thread::sleep_for(std::chrono::milliseconds(1000));
//     QString pubName_1 = "ORS_CMOR/Device01"; // 固定话题
//     QString subName_1 = "ORS_CMOR/Device03"; // 固定话题
//     //createAndSubscribeNewNode(0,pubName_1,subName_1);

//     // QString msgContent = "pubsher success 0218";
//     // if(msgContent.isEmpty())
//     // {
//     //     msgContent = "default command";
//     // }

//     // CNP_RESULT result = ddsClient_->publishCommand(msgContent);
//     // if(result == CNP_RESULT::CNP_PUBLISH_SUCCESS)
//     // {
//     //     qDebug() << "Message published successfully:" << msgContent;
//     // }
//     // else
//     // {
//     //     qDebug() << "Failed to publish message:" << msgContent;
//     // }
//     // std::this_thread::sleep_for(std::chrono::milliseconds(500));

// }

std::atomic<bool> shouldExit(false);
// void signalHandler(int signum) {
//     if (signum == SIGINT) {
//         std::cout << "Received Ctrl + C. Exiting..." << std::endl;
//         shouldExit = true;
//     }
// }

// ���Ļص�����
void subscribeCallback(const CnpMsg& msg) {
    std::cout << "Received message: " << msg.content() << std::endl;
}

void MainWindow::initNode()
{
    CNP_DOMAIN_ID domain = 0;
    std::string serverAppID = "ORS_CMOR";
    CNPServer subscriber(domain, serverAppID);
    CNP_RESULT result = subscriber.subscribeCmdRequest(subscribeCallback);
    if (result == CNP_RESULT::CNP_SUBSCRIBE_SUCCESS) {
        std::cout << "Subscribed successfully. Waiting for messages..." << std::endl;
        // ��ģ���������
        // while (!shouldExit) {
        //     // std::this_thread::sleep_for(std::chrono::seconds(1));
        // }
    }
    else {
        std::cout << "Failed to subscribe." << std::endl;
    }
}


void MainWindow::on_msgStatuReceived(const QString &msg)
{
    // 当接收到订阅消息时，在 UI 中显示或记录
    qDebug() << "MainWindow received message:" << msg;
    // 假设有一个 QTextEdit 控件显示消息，objectName 为 textEditReceived
    //ui->textEditReceived->append(msg);
    processStatuMessage(msg);
}

void MainWindow::on_msgEventReceived(const QString &msg)
{
    // 当接收到订阅消息时，在 UI 中显示或记录
    qDebug() << "MainWindow received message:" << msg;
    // 假设有一个 QTextEdit 控件显示消息，objectName 为 textEditReceived
    //ui->textEditReceived->append(msg);
    processEventMessage(msg);
}


void MainWindow::createAndSubscribeNewNode(uint32_t domainId, const QString& deviceID)
{
    // 1. 创建新的DDS节点
    DdsClientWrapper* newClient = new DdsClientWrapper(this);

    // 2. 初始化节点（可以传入不同的domain和topic）
    //uint32_t domainId = 0; // 或从UI/配置获取
    // QString pubName = pubTopic; // 固定话题
    // QString subName = subTopic; // 固定话题


    if(!newClient->initialize(domainId, deviceID)) {
        qWarning() << "Failed to initialize new DDS node";
        delete newClient;
        return;
    }

    // 3. 开始订阅
    if(newClient->startSubscription() == CNP_RESULT::CNP_SUBSCRIBE_SUCCESS) {
        qDebug() << "New DDS node subscribed successfully to deviceID:" << deviceID;

        // 连接信号槽
        connect(newClient, &DdsClientWrapper::msgStatuReceived,
                this, &MainWindow::on_msgStatuReceived);

        connect(newClient, &DdsClientWrapper::msgEventReceived,
                this, &MainWindow::on_msgEventReceived);
        // 保存到列表
        ddsClients_.append(newClient);
    } else {
        qWarning() << "Failed to subscribe new DDS node";
        delete newClient;
    }
}

void MainWindow::processStatuMessage(const QString &jsonString) {
    // 将 QString 转换为 QByteArray 进行 JSON 解析
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8(), &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qWarning() << "解析 JSON 出错:" << parseError.errorString();
        return;
    }
    if (!doc.isObject()) {
        qWarning() << "JSON 数据不是对象格式";
        return;
    }

    QJsonObject jsonObj = doc.object();

    // 获取 device_id 字段
    QString deviceIdStr = jsonObj.value("device_id").toString();

    // 获取 message_id 字段作为 timestamp
    QString timestampStr = jsonObj.value("message_id").toString();

    // 解析 content 对象
    QJsonObject contentObj = jsonObj.value("content").toObject();
    QHash<QString, QString> content;
    for (auto it = contentObj.begin(); it != contentObj.end(); ++it) {
        content.insert(it.key(), it.value().toString());
    }

    // 构造 mMessage 对象
    mMessage msg;
    msg.device_id = deviceIdStr;
    msg.timestamp = timestampStr;
    msg.mContent = content;

    // 将消息保存到全局变量 mStatus 中，以 deviceIdStr 作为键
    mStatus.insert(deviceIdStr, msg);
}


void MainWindow::processEventMessage(const QString &jsonString) {
    // 将 QString 转换为 QByteArray 进行 JSON 解析
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(jsonString.toUtf8(), &parseError);
    if (parseError.error != QJsonParseError::NoError) {
        qWarning() << "解析 JSON 出错:" << parseError.errorString();
        return;
    }
    if (!doc.isObject()) {
        qWarning() << "JSON 数据不是对象格式";
        return;
    }

    QJsonObject jsonObj = doc.object();

    // 获取 device_id 字段
    QString deviceIdStr = jsonObj.value("device_id").toString();

    // 获取 message_id 字段作为 timestamp
    QString timestampStr = jsonObj.value("message_id").toString();

    // 解析 content 对象
    QJsonObject contentObj = jsonObj.value("content").toObject();
    QHash<QString, QString> content;
    for (auto it = contentObj.begin(); it != contentObj.end(); ++it) {
        content.insert(it.key(), it.value().toString());
    }

    // 构造 mMessage 对象
    mMessage msg;
    msg.device_id = deviceIdStr;
    msg.timestamp = timestampStr;
    msg.mContent = content;

    // 将消息保存到全局变量 mStatus 中，以 deviceIdStr 作为键
    mEvent.insert(deviceIdStr, msg);
}


void MainWindow::upEventMsg(const QStringList &evt)
{
    // std::cout<<"in upEventMsg"<<std::endl;


    QString messageType = evt.value(0);
    QString messageContent = evt.value(1);

    // 如果当前的filters不为空，且过滤条件匹配，就执行appendMessage
    if (currentFilters.isEmpty() || currentFilters.contains(messageType)) {
        appendMessage(messageContent, messageType);
    }
}
